package com.neuedu.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.neuedu.entity.Register;
import com.neuedu.exception.NeueduException;
import com.neuedu.mapper.RegisterMapper;
import com.neuedu.query.EmpCountQuery;
import com.neuedu.service.NeueduPayService;
import com.neuedu.service.RegisterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.util.NeueduPayConfig;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 挂号信息表 服务实现类
 * </p>
 *
 * @author LiYang
 * @since 2024-11-11
 */
@Service
public class RegisterServiceImpl extends ServiceImpl<RegisterMapper, Register> implements RegisterService {
    @Resource
    RegisterMapper registerMapper;
    @Resource
    NeueduPayService neueduPayService;
    @Override
    public IPage<Register> list(Integer pageNo, Integer pageSize, String caseNumber, String realName, Long openId, Integer visitState) {
        LocalDate today = LocalDate.now();
        QueryWrapper<Register> wrapper = new QueryWrapper<>();
        wrapper.eq("employee_id", openId) // 医生   获取今天的日期
                .between("visit_date", LocalDateTime.of(today, LocalTime.MIN), LocalDateTime.of(today, LocalTime.MAX));
        if (null != visitState) {
            wrapper.eq("visit_state", visitState);
        }
        if(StringUtils.isNotBlank(caseNumber)) {
            wrapper.like("case_number", caseNumber);
        }
        if (StringUtils.isNotBlank(realName)) {
            wrapper.like("real_name", realName);
        }

        return this.page(new Page<>(pageNo, pageSize), wrapper);
    }
    @Override
    public int getRegisterCount(LocalDate visitDate, String noon, Long employeeId) {
        return registerMapper.getRegisterCount(new EmpCountQuery(visitDate, employeeId, noon));
    }

    @Override
    public String add(Register register) throws AlipayApiException{
        this.save(register);
        return neueduPayService.neueduPay(register.getCaseNumber(), register.getRegistMoney(), "挂号费");
    }
    @Override
    public String updatePay(HttpServletRequest request) {
        try {
            Map<String,String> params = new HashMap<String,String>(); // 将所有参数保存在map中
            Map<String, String[]> parameterMap = request.getParameterMap();// 获取所有参数
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {// 遍历所有参数
                String[] values = entry.getValue();
                if (values.length == 1) {
                    params.put(entry.getKey(), values[0]);
                } else {
                    params.put(entry.getKey(),  String.join("," ,values));
                }
            }
            final boolean flag = AlipaySignature.rsaCheckV1(params, NeueduPayConfig.ALIPAYPUBLICKEY, NeueduPayConfig.CHARSET, NeueduPayConfig.SIGNTYPE);
            if (flag) {  // 支付成功处理 请求
                final String caseNumber = params.get("out_trade_no"); // 订单号
                Register register = new Register();
                register.setVisitState(1);
                UpdateWrapper<Register> wrapper = new UpdateWrapper<>();
                wrapper.eq("case_number", caseNumber);
                this.update(register, wrapper);
            }
            return "success";
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "fail";
        }
    }
    public Boolean call(Integer num, String realName) {
        System.out.println("1111111111111111");
        String text = String.format("请%d号患者%s来就诊", num, realName);
        ActiveXComponent sap = new ActiveXComponent("Sapi.SpVoice");
        try {
            // 音量 0-100
            sap.setProperty("Volume", new Variant(100));
            // 语音朗读速度 -10 到 +10
            sap.setProperty("Rate", new Variant(-2));
            // 获取执行对象
            Dispatch sapo = sap.getObject();
            // 执行朗读
            Dispatch.call(sapo, "Speak", new Variant(text));
            // 关闭执行对象
            sapo.safeRelease();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭应用程序连接
            sap.safeRelease();
        }
        return true;
    }

    @Override
    public Register jiezhen(Integer id) {
        Register register = new Register(id, 2);
        this.updateById(register);
        return this.getById(id);
    }

    @Override
    public Register getByCaseNumber(String caseNumber) {
        LambdaQueryWrapper<Register> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Register::getCaseNumber, caseNumber);
        final Register register = this.getOne(wrapper);
        if (null ==register){ //避免空指针异常
            throw new NeueduException("病历号错误");
        }
        return register;
    }
    @Override
    public List<Register> getByName(String realName) {
        QueryWrapper<Register> wrapper = new QueryWrapper<>();
        wrapper.eq("real_name", realName);
        return this.list(wrapper);
    }
    @Override
    public IPage<Register> getRegisterByFinish(Integer pageNo, Integer pageSize, String caseNumber, String realName) {
//        LocalDate today = LocalDate.now();
        return this.lambdaQuery()
                .eq(Register::getVisitState, 3)
//                .between(Register::getVisitDate, LocalDateTime.of(today, LocalTime.MIN), LocalDateTime.of(today, LocalTime.MAX))
                .like(org.springframework.util.StringUtils.hasText(caseNumber), Register::getCaseNumber, caseNumber)
                .like(org.springframework.util.StringUtils.hasText(realName), Register::getRealName, realName)
                .page(new Page<>(pageNo, pageSize));
    }

    @Override
    public Boolean cancelRegister(String caseNumber) {
        Register register = this.getByCaseNumber(caseNumber);
        register.setVisitState(4);
        return this.updateById(register);
    }
}
